<template>
  <div class="step-panel">
    <h2>{{ stepTitle }}</h2>

    <!-- 子步骤导航 -->
    <div class="substeps-nav">
      <div
        v-for="(substep, i) in substeps"
        :key="i"
        class="substep-item"
        :class="{
          'substep-active': currentSubstep === i + 1,
          'substep-completed': currentSubstep > i + 1,
          'substep-disabled': currentSubstep < i + 1,
        }"
        @click="navigateToSubstep(i + 1)"
      >
        <span>{{ i + 1 }}</span>
        <span>{{ substep.title }}</span>
      </div>
    </div>

    <!-- 子步骤1：健康评估 -->
    <div v-if="currentSubstep === 1" class="substep-content">
      <h3>健康评估</h3>

      <!-- 疾病情况 -->
      <div class="form-section">
        <label class="section-title">疾病情况（可多选） <span class="required">*</span></label>
        <div class="tag-group">
          <label
            class="tag-item"
            v-for="(disease, idx) in diseaseOptions"
            :key="idx"
          >
            <input
              type="checkbox"
              v-model="localFormData.healthAssessment.diseaseDiagnosis"
              :value="disease"
            />
            {{ disease }}
          </label>
          <label class="tag-item">
            <input
              type="checkbox"
              v-model="localFormData.healthAssessment.diseaseDiagnosis"
              value="其他"
              @change="toggleOtherDisease"
            />
            其他
          </label>
          <div
            v-if="localFormData.healthAssessment.showOtherDisease"
            class="other-input"
          >
            <input
              type="text"
              v-model="localFormData.healthAssessment.otherDisease"
              placeholder="请输入其他疾病"
              maxlength="20"
            />
          </div>
        </div>
      </div>

      <!-- 用药情况 -->
      <div class="form-section">
        <label class="section-title">用药情况</label>
        <div
          v-for="(medicine, mIdx) in localFormData.healthAssessment.medicationInfo"
          :key="mIdx"
          class="medicine-item"
        >
          <div class="form-grid">
            <div class="form-group">
              <label>药物名称</label>
              <input
                type="text"
                v-model="medicine.name"
                placeholder="请输入药物名称"
                maxlength="20"
              />
            </div>
            <div class="form-group">
              <label>服药方法</label>
              <input
                type="text"
                v-model="medicine.method"
                placeholder="如：每日3次"
                maxlength="20"
              />
            </div>
            <div class="form-group">
              <label>用药剂量</label>
              <input
                type="text"
                v-model="medicine.dosage"
                placeholder="如：1片/次"
                maxlength="20"
              />
            </div>
            <div class="form-group action-group">
              <label>&nbsp;</label>
              <button
                type="button"
                class="remove-btn"
                @click="removeMedicine(mIdx)"
                :disabled="localFormData.healthAssessment.medicationInfo.length <= 1"
              >
                - 删除
              </button>
            </div>
          </div>
        </div>
        <button type="button" class="add-btn" @click="addMedicine">
          + 添加用药
        </button>
      </div>

      <!-- 近30天风险事件 -->
      <div class="form-section">
        <label class="section-title">近30天内风险事件 <span class="required">*</span></label>
        <div
          v-for="(event, eIdx) in riskEvents"
          :key="eIdx"
          class="risk-event-item"
        >
          <label>{{ event.name }}</label>
          <div class="radio-group">
            <label v-for="n in 4" :key="n">
              <input
                type="radio"
                v-model="localFormData.healthAssessment.riskFactors[eIdx].count"
                :value="n - 1"
                required
              />
              {{ n - 1 }}次
            </label>
          </div>
        </div>
      </div>

      <!-- 身体健康情况 -->
      <div class="form-section">
        <label class="section-title">身体健康情况 <span class="required">*</span></label>
        
        <!-- 伤口情况 -->
        <div class="health-condition-item">
          <label>伤口情况</label>
          <div class="tag-group">
            <label
              class="tag-item"
              v-for="(option, oIdx) in healthConditions[0].options"
              :key="oIdx"
            >
              <input
                type="checkbox"
                v-model="localFormData.healthAssessment.woundCondition"
                :value="option"
              />
              {{ option }}
            </label>
            <label class="tag-item">
              <input
                type="checkbox"
                v-model="localFormData.healthAssessment.woundCondition"
                value="其他"
                @change="toggleOtherCondition('woundCondition')"
              />
              其他
            </label>
            <div
              v-if="localFormData.healthAssessment.showOtherWound"
              class="other-input"
            >
              <input
                type="text"
                v-model="localFormData.healthAssessment.otherWound"
                placeholder="请补充说明"
                maxlength="20"
              />
            </div>
          </div>
        </div>

        <!-- 特殊医疗照护情况 -->
        <div class="health-condition-item">
          <label>特殊医疗照护情况</label>
          <div class="tag-group">
            <label
              class="tag-item"
              v-for="(option, oIdx) in healthConditions[1].options"
              :key="oIdx"
            >
              <input
                type="checkbox"
                v-model="localFormData.healthAssessment.specialMedicalCare"
                :value="option"
              />
              {{ option }}
            </label>
            <label class="tag-item">
              <input
                type="checkbox"
                v-model="localFormData.healthAssessment.specialMedicalCare"
                value="其他"
                @change="toggleOtherCondition('specialMedicalCare')"
              />
              其他
            </label>
            <div
              v-if="localFormData.healthAssessment.showOtherMedicalCare"
              class="other-input"
            >
              <input
                type="text"
                v-model="localFormData.healthAssessment.otherMedicalCare"
                placeholder="请补充说明"
                maxlength="20"
              />
            </div>
          </div>
        </div>

        <!-- 自理能力 -->
        <div class="health-condition-item">
          <label>自理能力</label>
          <div class="tag-group">
            <label
              class="tag-item"
              v-for="(option, oIdx) in healthConditions[2].options"
              :key="oIdx"
            >
              <input
                type="checkbox"
                v-model="localFormData.healthAssessment.selfCareAbility"
                :value="option"
              />
              {{ option }}
            </label>
            <label class="tag-item">
              <input
                type="checkbox"
                v-model="localFormData.healthAssessment.selfCareAbility"
                value="其他"
                @change="toggleOtherCondition('selfCareAbility')"
              />
              其他
            </label>
            <div
              v-if="localFormData.healthAssessment.showOtherSelfCare"
              class="other-input"
            >
              <input
                type="text"
                v-model="localFormData.healthAssessment.otherSelfCare"
                placeholder="请补充说明"
                maxlength="20"
              />
            </div>
          </div>
        </div>

        <!-- 痴呆前兆 -->
        <div class="health-condition-item">
          <label>痴呆前兆</label>
          <div class="tag-group">
            <label
              class="tag-item"
              v-for="(option, oIdx) in healthConditions[3].options"
              :key="oIdx"
            >
              <input
                type="checkbox"
                v-model="localFormData.healthAssessment.dementiaPrecursors"
                :value="option"
              />
              {{ option }}
            </label>
            <label class="tag-item">
              <input
                type="checkbox"
                v-model="localFormData.healthAssessment.dementiaPrecursors"
                value="其他"
                @change="toggleOtherCondition('dementiaPrecursors')"
              />
              其他
            </label>
            <div
              v-if="localFormData.healthAssessment.showOtherDementia"
              class="other-input"
            >
              <input
                type="text"
                v-model="localFormData.healthAssessment.otherDementia"
                placeholder="请补充说明"
                maxlength="20"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 其他情况说明 -->
      <div class="form-section">
        <label class="section-title">其他情况说明</label>
        <div class="form-group">
          <textarea
            v-model="localFormData.healthAssessment.otherConditions"
            placeholder="请输入其他需要说明的健康情况（选填）"
            rows="4"
            maxlength="500"
            class="other-textarea"
          ></textarea>
          <div class="char-count">
            {{ localFormData.healthAssessment.otherConditions?.length || 0 }}/500
          </div>
        </div>
      </div>

      <!-- 体检报告上传 -->
      <div class="form-section">
        <label class="section-title">近期体检报告</label>
        <div class="upload-group">
          <div class="upload-item">
            <div class="upload-wrapper">
              <div
                class="upload-area medical-upload-area"
                @click="triggerFileInput('medicalReport')"
              >
                <input
                  type="file"
                  accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
                  ref="medicalReportInput"
                  @change="handleMedicalReportUpload($event)"
                  class="upload-input"
                  style="display: none"
                />
                <div
                  v-if="!localFormData.healthAssessment.medicalReport"
                  class="upload-placeholder"
                >
                  <span class="upload-icon">📄</span>
                  <span class="upload-text">点击上传体检报告</span>
                  <span class="upload-subtext">支持PDF、Word、图片格式，文件大小不超过60MB</span>
                </div>
                <div v-else class="file-info-large">
                  <div class="file-icon">📄</div>
                  <div class="file-details">
                    <span class="file-name">{{ localFormData.healthAssessment.medicalReport.name }}</span>
                    <span class="file-size">({{ formatFileSize(localFormData.healthAssessment.medicalReport.size) }})</span>
                  </div>
                  <button
                    type="button"
                    class="remove-btn"
                    @click.stop="clearMedicalReport"
                  >
                    删除
                  </button>
                </div>
              </div>
              <div class="upload-hint">
                请上传近期的体检报告，支持PDF、Word、JPG、PNG格式，文件大小不超过60MB
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="substep-actions">
        <button @click="$emit('prev')">上一步</button>
        <button @click="saveAndNextHealth" :disabled="!isHealthAssessmentValid || saving">
          {{ saving ? '保存中...' : '下一步' }}
        </button>
      </div>
    </div>

    <!-- 子步骤2：能力评估 -->
    <div v-if="currentSubstep === 2" class="substep-content">
      <h3>能力评估</h3>
      
      <!-- 自理能力评估 -->
      <div class="assessment-section">
        <h4>一、自理能力评估</h4>
        <div class="assessment-questions">
          <div
            v-for="(question, qIdx) in selfCareQuestions"
            :key="'selfcare-' + qIdx"
            class="question-item"
          >
            <div class="question-title">
              <span class="question-number">{{ qIdx + 1 }}.</span>
              <span>{{ question.title }}</span>
            </div>
            <div class="radio-group">
              <label v-for="(option, oIdx) in question.options" :key="oIdx">
                <input
                  type="radio"
                  v-model="localFormData.abilityAssessment.selfCareAbility[qIdx]"
                  :value="option.score"
                  required
                />
                {{ option.label }}（{{ option.score }}分）
              </label>
            </div>
          </div>
        </div>
      </div>

      <!-- 精神状态评估 -->
      <div class="assessment-section">
        <h4>二、精神状态评估</h4>
        <div class="assessment-questions">
          <div
            v-for="(question, qIdx) in mentalStatusQuestions"
            :key="'mental-' + qIdx"
            class="question-item"
          >
            <div class="question-title">
              <span class="question-number">{{ qIdx + 1 }}.</span>
              <span>{{ question.title }}</span>
            </div>
            <div class="radio-group">
              <label v-for="(option, oIdx) in question.options" :key="oIdx">
                <input
                  type="radio"
                  v-model="localFormData.abilityAssessment.mentalStatus[qIdx]"
                  :value="option.score"
                  required
                />
                {{ option.label }}（{{ option.score }}分）
              </label>
            </div>
          </div>
        </div>
      </div>

      <!-- 感知觉与社会参与 -->
      <div class="assessment-section">
        <h4>三、感知觉与社会参与</h4>
        <div class="assessment-questions">
          <div
            v-for="(question, qIdx) in perceptionSocialQuestions"
            :key="'perception-' + qIdx"
            class="question-item"
          >
            <div class="question-title">
              <span class="question-number">{{ qIdx + 1 }}.</span>
              <span>{{ question.title }}</span>
            </div>
            <div class="radio-group">
              <label v-for="(option, oIdx) in question.options" :key="oIdx">
                <input
                  type="radio"
                  v-model="localFormData.abilityAssessment.perceptionSocial[qIdx]"
                  :value="option.score"
                  required
                />
                {{ option.label }}（{{ option.score }}分）
              </label>
            </div>
          </div>
        </div>
      </div>

      <div class="substep-actions">
        <button @click="prevSubstep">上一步</button>
        <button @click="saveAndNextAbility" :disabled="!isAbilityAssessmentValid || saving">
          {{ saving ? '保存中...' : '下一步' }}
        </button>
      </div>
    </div>

    <!-- 子步骤3：评估报告 -->
    <div v-if="currentSubstep === 3" class="substep-content">
      <h3>评估报告</h3>

      <!-- 能力评估结果 -->
      <div class="report-section">
        <h4>一、能力评估结果</h4>
        
        <!-- 自理能力得分 -->
        <div class="score-category">
          <h5>自理能力评估</h5>
          <div class="score-details">
            <div
              v-for="(question, qIdx) in selfCareQuestions"
              :key="'selfcare-report-' + qIdx"
              class="score-item"
            >
              <span>{{ question.title }}</span>
              <span class="score-value">{{ localFormData.abilityAssessment.selfCareAbility[qIdx] || 0 }}分</span>
            </div>
            <div class="category-total">
              <strong>自理能力总分：{{ selfCareTotalScore }}分</strong>
            </div>
          </div>
        </div>

        <!-- 精神状态得分 -->
        <div class="score-category">
          <h5>精神状态评估</h5>
          <div class="score-details">
            <div
              v-for="(question, qIdx) in mentalStatusQuestions"
              :key="'mental-report-' + qIdx"
              class="score-item"
            >
              <span>{{ question.title }}</span>
              <span class="score-value">{{ localFormData.abilityAssessment.mentalStatus[qIdx] || 0 }}分</span>
            </div>
            <div class="category-total">
              <strong>精神状态总分：{{ mentalStatusTotalScore }}分</strong>
            </div>
          </div>
        </div>

        <!-- 感知觉与社会参与得分 -->
        <div class="score-category">
          <h5>感知觉与社会参与</h5>
          <div class="score-details">
            <div
              v-for="(question, qIdx) in perceptionSocialQuestions"
              :key="'perception-report-' + qIdx"
              class="score-item"
            >
              <span>{{ question.title }}</span>
              <span class="score-value">{{ localFormData.abilityAssessment.perceptionSocial[qIdx] || 0 }}分</span>
            </div>
            <div class="category-total">
              <strong>感知觉与社会参与总分：{{ perceptionSocialTotalScore }}分</strong>
            </div>
          </div>
        </div>

        <div class="total-score">
          <strong>能力评估总分：{{ totalAbilityScore }}分</strong>
          <span class="level-tag">能力初步等级：{{ getAbilityLevel(totalAbilityScore) }}</span>
        </div>
      </div>

      <!-- 护理等级结果 -->
      <div class="report-section">
        <h4>二、护理等级结果</h4>
        <div class="form-group">
          <label>能力等级变更依据（可多选） <span class="required">*</span></label>
          <div class="tag-group">
            <label
              class="tag-item"
              v-for="(basis, bIdx) in levelChangeBasis"
              :key="bIdx"
            >
              <input
                type="checkbox"
                v-model="localFormData.assessmentReport.changeBasis"
                :value="basis"
              />
              {{ basis }}
            </label>
            <label class="tag-item">
              <input
                type="checkbox"
                v-model="localFormData.assessmentReport.changeBasis"
                value="其他"
                @change="toggleReportOtherBasis"
              />
              其他
            </label>
          </div>
          <div
            v-if="localFormData.assessmentReport.showOtherBasis"
            class="other-input"
          >
            <input
              type="text"
              v-model="localFormData.assessmentReport.otherBasis"
              placeholder="请补充其他依据"
              maxlength="100"
            />
          </div>
        </div>

        <div class="form-group">
          <label>能力最终等级 <span class="required">*</span></label>
          <div class="radio-group">
            <label v-for="(level, lIdx) in finalAbilityLevels" :key="lIdx">
              <input
                type="radio"
                v-model="localFormData.assessmentReport.finalLevel"
                :value="level"
                required
              />
              {{ level }}
            </label>
          </div>
        </div>
      </div>

      <div class="substep-actions">
        <button @click="prevSubstep">上一步</button>
        <button @click="saveAndComplete" :disabled="!isReportValid || saving">
          {{ saving ? '保存中...' : '完成第二步' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { addHealthAssessment, updateHealthAssessment } from "@/api/le/healthAssessment"
import { addAbilityAssessment, updateAbilityAssessment } from "@/api/le/abilityAssessment"
import { addAssessmentReport, updateAssessmentReport } from "@/api/le/assessmentReport"

const props = defineProps({
  formData: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['next', 'prev', 'update:form-data'])

// 步骤配置
const stepTitle = '第二步：评估流程'
const substeps = [
  { title: "健康评估" },
  { title: "能力评估" },
  { title: "评估报告" },
]

// 健康评估选项配置
const diseaseOptions = [
  "无疾病",
  "冠心病",
  "高血压",
  "糖尿病",
  "心脏病",
  "脑血管病",
  "关节炎",
  "呼吸系统疾病",
]

const riskEvents = [
  { name: "跌倒" },
  { name: "走失" },
  { name: "噎食" },
  { name: "自杀" },
  { name: "昏迷" },
]

const healthConditions = [
  {
    name: "伤口情况",
    options: ["无", "擦伤", "烧烫伤", "术后伤口","糖尿病足溃疡"],
  },
  {
    name: "特殊医疗照护情况",
    options: ["无", "胃管", "尿管", "气管切开", "无创呼吸机", "透析"],
  },
  {
    name: "自理能力",
    options: ["不能自理", "轻度依赖", "中度依赖", "重度依赖"],
  },
  {
    name: "痴呆前兆",
    options: ["行为异常", "记忆障碍", "日常生活能力减退", "呆坐"],
  },
]

// 能力评估问题配置
const selfCareQuestions = [
  {
    title: "进食：使用适当的器具将食物送入嘴中并咽下",
    options: [
      { label: "独立完成，不需要协助", score: 5 },
      { label: "在他人语言指导或照看下完成", score: 4 },
      { label: "需要他人协助，但以自身完成为主", score: 3 },
      { label: "主要依靠协助，自身能予配合", score: 2 },
      { label: "完全依赖", score: 0 },
    ],
  },
  {
    title: "洗澡：清洗和擦干身体",
    options: [
      { label: "独立完成，不需要协助", score: 5 },
      { label: "在他人语言指导或照看下完成", score: 4 },
      { label: "需要他人协助，但以自身完成为主", score: 3 },
      { label: "主要依靠协助，自身能予配合", score: 2 },
      { label: "完全依赖", score: 1 },
    ],
  },
  {
    title: "修饰：指洗脸、刷牙、梳头、刮脸、剪指（趾）甲等",
    options: [
      { label: "独立完成，不需要协助", score: 5 },
      { label: "在他人语言指导或照看下完成", score: 4 },
      { label: "需要他人协助，但以自身完成为主", score: 3 },
      { label: "主要依靠协助，自身能予配合", score: 2 },
      { label: "完全依赖", score: 1 },
    ],
  } 
]

const mentalStatusQuestions = [
  {
    title: "认知功能：包括记忆力、定向力、注意力、计算力等",
    options: [
      { label: "认知正常", score: 5 },
      { label: "轻度认知障碍", score: 4 },
      { label: "中度认知障碍", score: 3 },
      { label: "重度认知障碍", score: 2 },
      { label: "完全丧失", score: 1 },
    ],
  },
  {
    title: "攻击行为：包括言语攻击和身体攻击",
    options: [
      { label: "无攻击行为", score: 5 },
      { label: "偶尔有言语攻击", score: 4 },
      { label: "经常有言语攻击", score: 3 },
      { label: "偶尔有身体攻击", score: 2 },
      { label: "经常有身体攻击", score: 1 },
    ],
  },
  {
    title: "抑郁症状：包括情绪低落、言语减少、兴趣减退等",
    options: [
      { label: "无抑郁症状", score: 5 },
      { label: "偶尔情绪低落", score: 4 },
      { label: "经常情绪低落", score: 3 },
      { label: "持续情绪低落", score: 2 },
      { label: "严重抑郁状态", score: 1 },
    ],
  },
]

const perceptionSocialQuestions = [
  {
    title: "视力",
    options: [
      { label: "视力正常", score: 5 },
      { label: "轻度视力障碍", score: 4 },
      { label: "中度视力障碍", score: 3 },
      { label: "重度视力障碍", score: 2 },
      { label: "完全失明", score: 1 },
    ],
  },
  {
    title: "听力",
    options: [
      { label: "听力正常", score: 5 },
      { label: "轻度听力障碍", score: 4 },
      { label: "中度听力障碍", score: 3 },
      { label: "重度听力障碍", score: 2 },
      { label: "完全失聪", score: 1 },
    ],
  },
  {
    title: "沟通交流：包括理解和表达",
    options: [
      { label: "沟通顺畅", score: 5 },
      { label: "轻度沟通困难", score: 4 },
      { label: "中度沟通困难", score: 3 },
      { label: "重度沟通困难", score: 2 },
      { label: "无法沟通", score: 1 },
    ],
  },
  {
    title: "社会参与：包括与人交往、参与活动等",
    options: [
      { label: "积极参与", score: 5 },
      { label: "偶尔参与", score: 4 },
      { label: "需要鼓励才参与", score: 3 },
      { label: "很少参与", score: 2 },
      { label: "不参与", score: 1 },
    ],
  },
]

const levelChangeBasis = ["已诊断疾病超过3项", "风险事件超过3次", "长期处于昏迷状态", "认知障碍/痴呆", "精神类疾病"]
const finalAbilityLevels = [
  "能力完好",
  "轻度失能", 
  "中度失能",
  "中重度失能",
  "重度失能",
]

// 本地状态
const currentSubstep = ref(1)
const saving = ref(false)
const localFormData = reactive(JSON.parse(JSON.stringify(props.formData)))
const medicalReportInput = ref(null)

// 初始化健康评估数据
const initHealthAssessment = () => {
  if (!localFormData.healthAssessment.diseaseDiagnosis) {
    localFormData.healthAssessment.diseaseDiagnosis = []
  }
  if (!localFormData.healthAssessment.medicationInfo) {
    localFormData.healthAssessment.medicationInfo = [{ name: "", method: "", dosage: "" }]
  }
  // 确保riskFactors数组与riskEvents数组保持同步
  if (!localFormData.healthAssessment.riskFactors || 
      localFormData.healthAssessment.riskFactors.length !== riskEvents.length) {
    localFormData.healthAssessment.riskFactors = riskEvents.map(event => ({ 
      name: event.name, 
      count: null 
    }))
  }
  if (!localFormData.healthAssessment.woundCondition) {
    localFormData.healthAssessment.woundCondition = []
  }
  if (!localFormData.healthAssessment.specialMedicalCare) {
    localFormData.healthAssessment.specialMedicalCare = []
  }
  if (!localFormData.healthAssessment.selfCareAbility) {
    localFormData.healthAssessment.selfCareAbility = []
  }
  if (!localFormData.healthAssessment.dementiaPrecursors) {
    localFormData.healthAssessment.dementiaPrecursors = []
  }
}

// 初始化能力评估数据
const initAbilityAssessment = () => {
  if (!localFormData.abilityAssessment.selfCareAbility) {
    localFormData.abilityAssessment.selfCareAbility = new Array(selfCareQuestions.length).fill(null)
  }
  if (!localFormData.abilityAssessment.mentalStatus) {
    localFormData.abilityAssessment.mentalStatus = new Array(mentalStatusQuestions.length).fill(null)
  }
  if (!localFormData.abilityAssessment.perceptionSocial) {
    localFormData.abilityAssessment.perceptionSocial = new Array(perceptionSocialQuestions.length).fill(null)
  }
  // 兼容旧字段
  if (!localFormData.abilityAssessment.answers) {
    localFormData.abilityAssessment.answers = []
  }
}

// 初始化评估报告数据
const initAssessmentReport = () => {
  if (!localFormData.assessmentReport.changeBasis) {
    localFormData.assessmentReport.changeBasis = []
  }
  if (!localFormData.assessmentReport.finalLevel) {
    localFormData.assessmentReport.finalLevel = ""
  }
}

// 调用初始化
initHealthAssessment()
initAbilityAssessment()
initAssessmentReport()

// ========== 新增：确保riskFactors数组正确初始化的额外检查 ==========
onMounted(() => {
  // 强制重新初始化riskFactors，确保与riskEvents数组同步
  if (!localFormData.healthAssessment.riskFactors || 
      localFormData.healthAssessment.riskFactors.length !== riskEvents.length) {
    localFormData.healthAssessment.riskFactors = riskEvents.map(event => ({
      name: event.name,
      count: null
    }));
  }
});

// 监听父组件数据变化
watch(() => props.formData, (newData) => {
  Object.assign(localFormData, newData)
  initHealthAssessment()
  initAbilityAssessment()
  initAssessmentReport()
}, { deep: true })

// 计算属性
// 健康评估验证
const isHealthAssessmentValid = computed(() => {
  const h = localFormData.healthAssessment
  if (h.diseaseDiagnosis.length === 0) return false
  if (h.diseaseDiagnosis.includes("其他") && !h.otherDisease) return false
  if (h.riskFactors.some((e) => e.count === null)) return false
  if (h.woundCondition.length === 0 || 
      h.specialMedicalCare.length === 0 || 
      h.selfCareAbility.length === 0 || 
      h.dementiaPrecursors.length === 0) return false
  return true
})

// 能力评估验证
const isAbilityAssessmentValid = computed(() => {
  const a = localFormData.abilityAssessment
  return a.selfCareAbility.every(score => score !== null) &&
         a.mentalStatus.every(score => score !== null) &&
         a.perceptionSocial.every(score => score !== null)
})

// 报告验证
const isReportValid = computed(() => {
  const r = localFormData.assessmentReport
  if (r.changeBasis.length === 0) return false
  if (r.changeBasis.includes("其他") && !r.otherBasis) return false
  return !!r.finalLevel
})

// 分数计算
const selfCareTotalScore = computed(() => {
  return localFormData.abilityAssessment.selfCareAbility.reduce((sum, score) => {
    return sum + (score || 0)
  }, 0)
})

const mentalStatusTotalScore = computed(() => {
  return localFormData.abilityAssessment.mentalStatus.reduce((sum, score) => {
    return sum + (score || 0)
  }, 0)
})

const perceptionSocialTotalScore = computed(() => {
  return localFormData.abilityAssessment.perceptionSocial.reduce((sum, score) => {
    return sum + (score || 0)
  }, 0)
})

const totalAbilityScore = computed(() => {
  return selfCareTotalScore.value + mentalStatusTotalScore.value + perceptionSocialTotalScore.value
})

// 保存健康评估数据
const saveHealthAssessment = async () => {
  if (!localFormData.elderlyId) {
    console.error('老人ID不存在')
    return false
  }

  try {
    saving.value = true
    
    // 构建后端需要的JSON数据
    const healthData = {
      elderlyId: localFormData.elderlyId,
      diseaseDiagnosis: JSON.stringify({
        diseases: localFormData.healthAssessment.diseaseDiagnosis,
        otherDisease: localFormData.healthAssessment.otherDisease
      }),
      medicationInfo: JSON.stringify(localFormData.healthAssessment.medicationInfo),
      riskFactors: JSON.stringify(localFormData.healthAssessment.riskFactors),
      woundCondition: JSON.stringify({
        conditions: localFormData.healthAssessment.woundCondition,
        other: localFormData.healthAssessment.otherWound || ''
      }),
      specialMedicalCare: JSON.stringify({
        conditions: localFormData.healthAssessment.specialMedicalCare,
        other: localFormData.healthAssessment.otherMedicalCare || ''
      }),
      selfCareAbility: JSON.stringify({
        conditions: localFormData.healthAssessment.selfCareAbility,
        other: localFormData.healthAssessment.otherSelfCare || ''
      }),
      dementiaPrecursors: JSON.stringify({
        conditions: localFormData.healthAssessment.dementiaPrecursors,
        other: localFormData.healthAssessment.otherDementia || ''
      }),
      otherConditions: JSON.stringify({
        text: localFormData.healthAssessment.otherConditions || ''
      }),
      assessmentStatus: '已完成'
    }

    // 如果有体检报告文件，使用FormData上传
    if (localFormData.healthAssessment.medicalReport) {
      const formData = new FormData()
      Object.keys(healthData).forEach(key => {
        formData.append(key, healthData[key])
      })
      formData.append('medicalReport', localFormData.healthAssessment.medicalReport)
      
      await addHealthAssessment(formData)
    } else {
      await addHealthAssessment(healthData)
    }
    
    return true
  } catch (error) {
    console.error('保存健康评估失败:', error)
    return false
  } finally {
    saving.value = false
  }
}

// 保存能力评估数据
const saveAbilityAssessment = async () => {
  if (!localFormData.elderlyId) {
    console.error('老人ID不存在')
    return false
  }

  try {
    saving.value = true
    
    // 构建能力评估数据
    const abilityData = {
      elderlyId: localFormData.elderlyId,
      selfCareAbility: JSON.stringify(
        selfCareQuestions.map((question, index) => ({
          question: question.title,
          score: localFormData.abilityAssessment.selfCareAbility[index],
          options: question.options
        }))
      ),
      mentalStatus: JSON.stringify(
        mentalStatusQuestions.map((question, index) => ({
          question: question.title,
          score: localFormData.abilityAssessment.mentalStatus[index],
          options: question.options
        }))
      ),
      perceptionSocialParticipation: JSON.stringify(
        perceptionSocialQuestions.map((question, index) => ({
          question: question.title,
          score: localFormData.abilityAssessment.perceptionSocial[index],
          options: question.options
        }))
      ),
      assessmentStatus: '已完成'
    }

    await addAbilityAssessment(abilityData)
    return true
  } catch (error) {
    console.error('保存能力评估失败:', error)
    return false
  } finally {
    saving.value = false
  }
}

// 保存评估报告数据
const saveAssessmentReport = async () => {
  if (!localFormData.elderlyId) {
    console.error('老人ID不存在')
    return false
  }

  try {
    saving.value = true
    
    // 构建评估报告数据
    const reportData = {
      elderlyId: localFormData.elderlyId,
      selfCareScore: selfCareTotalScore.value,
      mentalStatusScore: mentalStatusTotalScore.value,
      perceptionSocialScore: perceptionSocialTotalScore.value,
      estimatedTotalScore: totalAbilityScore.value,
      preliminaryAbilityLevel: getAbilityLevel(totalAbilityScore.value),
      levelChangeBasis: JSON.stringify(localFormData.assessmentReport.changeBasis),
      otherBasis: JSON.stringify({
        showOther: localFormData.assessmentReport.showOtherBasis,
        otherText: localFormData.assessmentReport.otherBasis || ''
      }),
      finalAbilityLevel: localFormData.assessmentReport.finalLevel,
      assessmentDate: new Date().toISOString().split('T')[0], // 当前日期
      assessmentStatus: '已完成'
    }

    await addAssessmentReport(reportData)
    return true
  } catch (error) {
    console.error('保存评估报告失败:', error)
    return false
  } finally {
    saving.value = false
  }
}

// 健康评估下一步方法
const saveAndNextHealth = async () => {
  if (!isHealthAssessmentValid.value) return
  
  const success = await saveHealthAssessment()
  if (success) {
    ElMessage.success('健康评估保存成功')
    nextSubstep()
  } else {
    alert('保存失败，请重试')
  }
}

// 能力评估下一步方法
const saveAndNextAbility = async () => {
  if (!isAbilityAssessmentValid.value) return
  
  const success = await saveAbilityAssessment()
  if (success) {
    ElMessage.success('能力评估保存成功')
    nextSubstep()
  } else {
    alert('保存失败，请重试')
  }
}

// 完成评估并保存报告
const saveAndComplete = async () => {
  if (!isReportValid.value) return
  
  const success = await saveAssessmentReport()
  if (success) {
    ElMessage.success('评估报告保存成功')
    completeStep()
  } else {
    alert('保存失败，请重试')
  }
}

// 导航方法
const navigateToSubstep = (substep) => {
  if (substep <= currentSubstep.value) {
    currentSubstep.value = substep
    updateFormData()
  }
}

const nextSubstep = () => {
  if (currentSubstep.value < substeps.length) {
    currentSubstep.value++
  }
  updateFormData()
}

const prevSubstep = () => {
  if (currentSubstep.value > 1) {
    currentSubstep.value--
  }
  updateFormData()
}

const completeStep = () => {
  updateFormData()
  emit('next')
}

// 更新表单数据
const updateFormData = () => {
  emit('update:form-data', localFormData)
}

// 健康评估操作方法
const toggleOtherDisease = (e) => {
  localFormData.healthAssessment.showOtherDisease = e.target.checked
  if (!e.target.checked) {
    localFormData.healthAssessment.otherDisease = ""
  }
  updateFormData()
}

const addMedicine = () => {
  localFormData.healthAssessment.medicationInfo.push({
    name: "",
    method: "",
    dosage: "",
  })
  updateFormData()
}

const removeMedicine = (index) => {
  if (localFormData.healthAssessment.medicationInfo.length > 1) {
    localFormData.healthAssessment.medicationInfo.splice(index, 1)
    updateFormData()
  }
}

const toggleOtherCondition = (type) => {
  const fieldMap = {
    'woundCondition': 'showOtherWound',
    'specialMedicalCare': 'showOtherMedicalCare', 
    'selfCareAbility': 'showOtherSelfCare',
    'dementiaPrecursors': 'showOtherDementia'
  }
  
  const showField = fieldMap[type]
  const selectedArray = localFormData.healthAssessment[type]
  
  localFormData.healthAssessment[showField] = selectedArray.includes("其他")
  
  if (!localFormData.healthAssessment[showField]) {
    const otherField = showField.replace('showOther', 'other')
    localFormData.healthAssessment[otherField] = ""
  }
  
  updateFormData()
}

// 评估报告操作方法
const toggleReportOtherBasis = (e) => {
  localFormData.assessmentReport.showOtherBasis = e.target.checked
  if (!e.target.checked) {
    localFormData.assessmentReport.otherBasis = ""
  }
  updateFormData()
}

// 文件上传方法
const triggerFileInput = (type) => {
  switch (type) {
    case "medicalReport":
      medicalReportInput.value?.click()
      break
  }
}

const handleMedicalReportUpload = (e) => {
  const file = e.target.files[0]
  if (!file) return

  const validTypes = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'image/jpeg',
    'image/png'
  ]
  
  const validExtensions = ['.pdf', '.doc', '.docx', '.jpg', '.jpeg', '.png']
  const fileExtension = '.' + file.name.split('.').pop().toLowerCase()
  
  if (!validTypes.includes(file.type) && !validExtensions.includes(fileExtension)) {
    alert('请上传PDF、Word或图片格式的文件')
    resetFileInput('medicalReport')
    return
  }

  const maxSize = 60 * 1024 * 1024
  if (file.size > maxSize) {
    alert('文件大小不能超过60MB')
    resetFileInput('medicalReport')
    return
  }

  localFormData.healthAssessment.medicalReport = file
  updateFormData()
}

const resetFileInput = (type) => {
  switch (type) {
    case "medicalReport":
      if (medicalReportInput.value) medicalReportInput.value.value = ""
      break
  }
}

const clearMedicalReport = () => {
  localFormData.healthAssessment.medicalReport = null
  resetFileInput('medicalReport')
  updateFormData()
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return "0 Bytes"
  const k = 1024
  const sizes = ["Bytes", "KB", "MB"]
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]
}

// 能力等级判定
const getAbilityLevel = (score) => {
  const maxScore = 50 // 自理能力15 + 精神状态15 + 感知觉20
  if (score >= 40) return "能力完好"
  if (score >= 31) return "轻度失能"
  if (score >= 21) return "中度失能"
  if (score >= 11) return "中重度失能"
  return "重度失能"
}
</script>

<style scoped>
/* 原有的所有样式保持不变 */
.step-panel h2 {
  color: #1f2937;
  margin-top: 0;
  padding-bottom: 15px;
  border-bottom: 1px solid #e5e7eb;
}

/* 子步骤样式 */
.substeps-nav {
  display: flex;
  margin: 20px 0 30px;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 10px;
}

.substep-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-right: 30px;
  color: #6b7280;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
}

.substep-item:hover:not(.substep-disabled) {
  color: #3b82f6;
}

.substep-item span:first-child {
  display: inline-block;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #e5e7eb;
  color: #6b7280;
  text-align: center;
  line-height: 24px;
  font-size: 12px;
  transition: all 0.3s ease;
}

.substep-active {
  color: #3b82f6;
}

.substep-active span:first-child {
  background-color: #3b82f6;
  color: white;
}

.substep-completed {
  color: #10b981;
}

.substep-completed span:first-child {
  background-color: #10b981;
  color: white;
}

.substep-disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

/* 表单样式 */
.substep-content {
  margin: 20px 0;
}

.form-section {
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  display: block;
  margin-bottom: 15px;
  font-weight: 600;
  color: #333;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #4b5563;
  font-weight: 500;
}

.required {
  color: #ef4444;
}

input,
select,
textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.other-textarea {
  resize: vertical;
  min-height: 80px;
}

.char-count {
  text-align: right;
  font-size: 12px;
  color: #6b7280;
  margin-top: 4px;
}

.radio-group {
  display: flex;
  gap: 20px;
  margin-top: 8px;
  /* flex-wrap: wrap; */
}

.radio-group label {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 0;
}

/* 标签组样式 */
.tag-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.tag-item {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 6px 12px;
  background-color: #f5f5f5;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.2s;
}

.tag-item:hover {
  background-color: #e5e7eb;
}

.tag-item input:checked + span {
  color: #3b82f6;
  font-weight: 500;
}

.other-input {
  margin-top: 10px;
  margin-left: 5px;
}

/* 药品项样式 */
.medicine-item {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 6px;
  margin-bottom: 15px;
}

.action-group {
  display: flex;
  align-items: flex-end;
}

.remove-btn {
  background-color: #fef2f2;
  color: #dc2626;
  border: none;
  padding: 4px 8px;
  border-radius: 3px;
  font-size: 12px;
  cursor: pointer;
}

.add-btn {
  background-color: #eff6ff;
  color: #2563eb;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 30px;
}

/* 风险事件和健康条件样式 */
.risk-event-item,
.health-condition-item {
  margin-bottom: 20px;
  padding: 10px;
  border-radius: 4px;
  background-color: #f9f9f9;
}

/* 问题项样式 */
.question-item {
  margin-bottom: 25px;
  padding: 15px;
  border-radius: 6px;
  background-color: #f9f9f9;
}

.question-title {
  margin-bottom: 10px;
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.question-number {
  font-weight: bold;
  color: #3b82f6;
}

/* 报告部分样式 */
.report-section {
  margin-bottom: 30px;
  padding: 15px;
  border-radius: 6px;
  background-color: #f9f9f9;
}

.score-details {
  margin-top: 10px;
}

.score-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px dashed #e0e0e0;
}

.total-score {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 2px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.level-tag {
  padding: 4px 10px;
  background-color: #e6f7ff;
  color: #1890ff;
  border-radius: 4px;
  font-size: 14px;
}

/* 上传区域样式 */
.upload-group {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.upload-item {
  margin-bottom: 10px;
}

.upload-wrapper {
  width: 100%;
}

.upload-area {
  width: 100%;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  transition: all 0.3s ease;
}

.upload-area:hover {
  border-color: #3b82f6;
  background-color: #f9fafb;
}

.medical-upload-area {
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-input {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  opacity: 0;
  cursor: pointer;
  z-index: 10;
}

.upload-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #9ca3af;
  text-align: center;
}

.upload-icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.upload-text {
  font-size: 14px;
  margin-bottom: 4px;
}

.upload-subtext {
  font-size: 12px;
  color: #6b7280;
}

.file-info-large {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  width: 100%;
}

.file-icon {
  font-size: 24px;
}

.file-details {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.file-name {
  font-weight: 500;
  color: #374151;
}

.file-size {
  font-size: 12px;
  color: #6b7280;
}

.upload-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #9ca3af;
}

/* 按钮区域样式 */
.substep-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 40px;
}

button {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

button:not(:disabled):hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

button:nth-of-type(1) {
  background-color: #f3f4f6;
  color: #1f2937;
}

button:nth-of-type(2),
button:last-child {
  background-color: #3b82f6;
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }

  .substeps-nav {
    flex-direction: column;
    gap: 10px;
  }

  .substep-item {
    margin-right: 0;
  }

  .tag-group {
    flex-direction: column;
    align-items: flex-start;
  }

  .radio-group {
    flex-direction: column;
    gap: 10px;
  }
}
</style>
